package com.css.dzj.dzjwgr.modules.boards.service.impl;

import com.css.dzj.dzjwgr.common.util.Constant;
import com.css.dzj.dzjwgr.common.util.R;
import com.css.dzj.dzjwgr.common.util.ServiceUtil;
import com.css.dzj.dzjwgr.common.util.SnowflakeId;
import com.css.dzj.dzjwgr.modules.boards.entity.BoardsEntity;
import com.css.dzj.dzjwgr.modules.boards.entity.QBoardsEntity;
import com.css.dzj.dzjwgr.modules.boards.mappper.BoardMapper;
import com.css.dzj.dzjwgr.modules.boards.service.BoardService;
import com.css.dzj.dzjwgr.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 宣传板实现层
 * @author wt
 * @date 2020\3\3 0003
 */
@Service
public class BoardServiceImpl implements BoardService {

    @Autowired
    private BoardMapper bMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private ServiceUtil serviceUtil;

    @Autowired
    private HttpServletRequest request;

    /**
     * 添加宣传板信息
     */
    @Override
    @Transactional
    public void add(BoardsEntity boardsEntity) {

        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                boardsEntity.setCreateUser(userInfo.getLoginName());
                boardsEntity.setCreateUserunit(userInfo.getOrgName());
            }
//            boardsEntity.setId(SnowflakeId.getId());
            boardsEntity.setDelFlag(Constant.NO_DELETE);
            boardsEntity.setCreateTime(new Date());
            boardsEntity.setStatte("0");

            bMapper.save(boardsEntity);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发布在新建的时候宣传板信息
     */
    @Override
    @Transactional
    public void saverelease(BoardsEntity boardsEntity) {

        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                boardsEntity.setCreateUser(userInfo.getLoginName());
                boardsEntity.setCreateUserunit(userInfo.getOrgName());
            }
//            boardsEntity.setId(SnowflakeId.getId());
            boardsEntity.setDelFlag(Constant.NO_DELETE);
            boardsEntity.setCreateTime(new Date());
            boardsEntity.setStatte("1");

            bMapper.save(boardsEntity);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改宣传板信息
     */
    @Override
    @Transactional
    public void update(BoardsEntity boardsEntity) {

    }

    /**
     * 通过id查询宣传板信息
     */
    @Override
    public BoardsEntity findById(String id) {

        if(StringUtils.isEmpty(id)){

            throw new RuntimeException("参数为空");
        }
        QBoardsEntity qBoard = QBoardsEntity.boardsEntity;
        return jpaQueryFactory
                .selectFrom(qBoard)
                .where(  qBoard.id.eq(id),
                        qBoard.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }

    /**
     * 分页查询宣传板信息
     */
    @Override
    public QueryResults<BoardsEntity> queryPage(Pageable pageable) {

        QBoardsEntity qBoard = QBoardsEntity.boardsEntity;
        Predicate predicate = qBoard.isNotNull().or(qBoard.isNull());
        predicate = ExpressionUtils.and(predicate, qBoard.delFlag.eq(Constant.NO_DELETE)) ;

        QueryResults<BoardsEntity> boardResults = jpaQueryFactory.selectFrom(qBoard)
                .where(
                        predicate
                )
                .orderBy(qBoard.createTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
        return boardResults;
    }

    /**
     * 删除宣传板信息
     */
    @Override
    @Transactional
    public Boolean delete(String id) {

        QBoardsEntity qBoard = QBoardsEntity.boardsEntity;
        if(StringUtils.isEmpty(id)){
            throw new RuntimeException("参数为空");
        }
        try{
            jpaQueryFactory
                    .update(qBoard)
                    .set(qBoard.delFlag,Constant.DELETE)
                    .where(
                            qBoard.id.eq(id),
                            qBoard.delFlag.eq(Constant.NO_DELETE)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 多条件分页查询宣传板信息
     */
    @Override
    public QueryResults<BoardsEntity> getXcbList(String createUser, String title, String createUserunit, String statte, String releaseStartTime, String releaseEndTime, Pageable pageable) {

        QBoardsEntity qBoard = QBoardsEntity.boardsEntity;

        Predicate predicate = qBoard.isNotNull().or(qBoard.isNull());
        predicate = ("".equals(createUser) || createUser == null) ? predicate : ExpressionUtils.and(predicate, qBoard.createUser.like("%"+createUser.trim()+"%"));
        predicate = ("".equals(title) || title == null) ? predicate : ExpressionUtils.and(predicate, qBoard.title.like("%"+title.trim()+"%"));
        predicate = ("".equals(createUserunit) || createUserunit == null) ? predicate : ExpressionUtils.and(predicate, qBoard.createUserunit.like("%"+createUserunit.trim()+"%"));
        predicate = ("".equals(statte) || statte == null) ? predicate : ExpressionUtils.and(predicate, qBoard.statte.eq(statte));

        if((StringUtils.isEmpty(releaseStartTime))&&(!StringUtils.isEmpty(releaseEndTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(releaseEndTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, qBoard.releaseTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(releaseStartTime))&&(StringUtils.isEmpty(releaseEndTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(releaseStartTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate,qBoard.releaseTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(releaseStartTime))&&(!StringUtils.isEmpty(releaseEndTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(releaseEndTime + " "+"23:59:59.999");
                startDate = sf.parse(releaseStartTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, qBoard.releaseTime.between(startDate,endDate));
        }

        predicate = ExpressionUtils.and(predicate, qBoard.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(qBoard)
                .where(
                        predicate
                )
                .orderBy(qBoard.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }




}
